package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import com.heima.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-03-01
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {
    @Autowired
    private ApUserService apUserService;

    //用户服务--用户认证列表查询
    @Override
    public PageResult<UserAuthDto> findByStatus(AuthDto dto) {
        //1. 设置查询条件
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserAuth::getStatus, dto.getStatus());
        }
        //2. 设置分页条件
        IPage<ApUserAuth> iPage = new Page<>(dto.getPage(), dto.getSize());
        //3. 分页查询
        IPage<ApUserAuth> userAuthIPage = page(iPage, queryWrapper);
        if (userAuthIPage == null || CollectionUtils.isEmpty(userAuthIPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4. 构造返回对象
        List<UserAuthDto> userAuthDtos = BeanHelper.copyWithCollection(userAuthIPage.getRecords(), UserAuthDto.class);
        return new PageResult<>(dto.getPage(), dto.getSize(), userAuthIPage.getTotal(), userAuthDtos);
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    //用户服务--认证信息审核通过或不通过
    @GlobalTransactional
    @Override
    public void authUser(AuthDto dto, int status) {
        //1. 获取认证ID
        Integer id = dto.getId();
        //2. 创建ApUserAuth实体类
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(id);
        apUserAuth.setStatus(status);
        //3. 修改认证状态
        boolean b = updateById(apUserAuth);
        if (!b) {
            log.error("修改用户认证状态失败，id={}", id);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //4. 判断是否通过审核
        if (status == 2) {
            // 没有通过审核，直接返回
            log.error("用户审核不通过，直接返回，id={}", id);

            return;
        }
        //5. 根据认证id获取对象
        ApUserAuth userAuth = getById(id);
        Integer apUserId = userAuth.getUserId();
        //5.1. 根据apUserId获取APUser对象
        ApUser apUser = apUserService.getById(apUserId);
        //6. 远程调用自媒体服务，创建/修改自媒体用户
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(apUserId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setStatus(9);
        wmUserDto.setPhone(apUser.getPhone());
        try {
            Integer wmUserId = wemediaFeign.save(wmUserDto);
            wmUserDto.setId(wmUserId);
        } catch (Exception e) {
            log.error("远程调用自媒体创建用户失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //7. 远程调用文章服务，创建/修改文章作者
        AuthorDto authorDto = new AuthorDto();
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        authorDto.setUserId(apUserId);
        authorDto.setWmUserId(wmUserDto.getId());
        try {
            Integer authorId = articleFeign.save(authorDto);
        } catch (Exception e) {
            log.error("远程调用作者服务，创建作者失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //8. 修改APP用户类型flag 0 - 普通用户 修改为 - 1 自媒体人
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if (!b1) {
            log.error("修改apUser的flag失败！id={}", apUserId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
